class Compiler {
    constructor(vm){
        this.el = vm.$el
        this.vm = vm
        this.methods = vm.$methods
        this.compile(this.el)
    }
    compile(el){
        let nodes = el.childNodes
        Array.from(nodes).forEach(node => {
            if(this.isTextNode(node)){
                this.compileText(node)
            }else if(this.isElementNode(node)){
                this.compileElement(node)
            }
            this.compile(node)
        });
    }
    //编译元素节点 处理指令
    compileElement(node){
        let attrs = node.attributes
        Array.from(attrs).forEach(attr => {
            let attrName = attr.name
            if(this.isDirective(attrName)){
                let key = attr.value
                if(this.isOnDirective(attrName)){
                    let event =  attrName.substr(5) //v-on:
                    this.addDirectiveListener(node, event, this.methods[key])
                }else {
                    attrName = attrName.substr(2)
                    this.update(node, key, attrName)
                }
            }
        })
    }
    update(node, key, attrName){
        let updateFn = this[attrName+'Update']
        updateFn && updateFn.call(this, node, this.vm[key], key)
        
    }
    textUpdate(node, value, key){
        node.textContent = value
        new Watcher(this.vm, key, nValue => {
            node.textContent = nValue
        })
    }
    modelUpdate(node, value, key){
        node.value = value
        new Watcher(this.vm, key, nValue => {
            node.value = nValue
        })
        node.addEventListener('input', () => {
            this.vm[key] = node.value
        })
    }
    addDirectiveListener(node, event, method){
        node.addEventListener(event, method)
    }
    //编译文本节点 处理插值表达式
    compileText(node){
        let reg = /\{\{(.+?)\}\}/
        let value = node.textContent
        if(reg.test(value)){
            let key = RegExp.$1.trim()
            node.textContent = node.textContent.replace(reg, this.vm[key])
            //创建watcher对象 数据改变更新视图
            new Watcher(this.vm, key, nValue => {
                node.textContent = nValue
            })
        }
    }
    isDirective(attrName){
        return attrName.startsWith('v-')
    }
    isOnDirective(attrName){
        return attrName.startsWith('v-on')
    }
    isElementNode(node){
        return node.nodeType === 1
    }
    isTextNode(node){
        return node.nodeType === 3
    }

}